package com.java.base.exercise.designmode.sharemode;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author RenPu
 * @Date 2021/6/27 11:17
 * @Version 1.0
 * @Description: 设计模式---享元设计模式
 **/
public class ShareMode {

    public static void main(String[] args) {
        BultPool bultPool = new BultPool();

        for (int i = 0; i < 20; i++) {
            Bult bult = bultPool.getBult();
            bult.lifeCycle += 1;
            System.out.println(bult);
        }


    }
}


//子弹实体类
class Bult {
    public UUID id = UUID.randomUUID();
    boolean living = true;
    int lifeCycle = 0;

    @Override
    public String toString() {
        return "Bult{" +
                "id=" + id +
                ", living=" + living +
                ", lifeCycle=" + lifeCycle +
                '}';
    }
}

//子弹池
class BultPool {

    //子弹集合
    List<Bult> list = new ArrayList<>();

    {
        for (int i = 0; i < 50; i++) {
            list.add(new Bult());

        }
    }


    /**
     * 获取子弹
     *
     * @return
     */
    public Bult getBult() {
        for (int i = 0; i < list.size(); i++) {
            Bult bult = list.get(i);
            if (!bult.living && bult.lifeCycle == 0) {
                return bult;
            } else {
                bult.living = false;
            }
        }
        return new Bult();

    }


}
